class LianZi {
    writerSize = 73;

    constructor(writerWidth) {
        this.writerSize = writerWidth;
    }


    init() {
        const code = this.getQueryString("code");
        this.getData(code,(data) => {
            this.drawPaper(data,(data) => {
                this.hzToWriter(data);
            });
        });
    }

    async getData(code, callback) {
        await $.get("/resource/data/grade/" + code + ".json", function (result, status) {
            let hzArr = [];
            const data = result.data;
            for (let str of data) {
                if ((/[\u4e00-\u9fa5]/).test(str)) {
                    hzArr.push(str);
                }
            }
            callback(hzArr);
        });
    }

    drawPaper(data,callback) {
        for (let i = 0; i < data.length; i++) {
            const itemHtml = this.getItemHtml('item-' + i);
            $("#paper-box").append(itemHtml);
        }
        callback(data);
    }

    hzToWriter(data) {
        for (let i = 0; i < data.length; i++) {
            this.addHanZiWriter(data[i], i);
        }


    }

    addHanZiWriter(hanZi, index) {
        const writer = HanziWriter.create('item-' + index, hanZi, {
            width: this.writerSize,
            height: this.writerSize,
            padding: 5,
            showCharacter: true,
            strokeColor: '#BBB'
        });
    }

    getItemHtml(id) {
        return `
        <svg xmlns="http://www.w3.org/2000/svg" width="` + this.writerSize + `" height="` + this.writerSize + `" class="font-box" id="` + id + `">
            <line x1="0" y1="0" x2="` + this.writerSize + `" y2="` + this.writerSize + `" stroke="#BBB" />
            <line x1="` + this.writerSize + `" y1="0" x2="0" y2="` + this.writerSize + `" stroke="#BBB" />
            <line x1="` + this.writerSize / 2 + `" y1="0" x2="` + this.writerSize / 2 + `" y2="` + this.writerSize + `" stroke="#DDD" />
            <line x1="0" y1="` + this.writerSize / 2 + `" x2="` + this.writerSize + `" y2="` + this.writerSize / 2 + `" stroke="#DDD" />
        </svg>
    `;
    }

    getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }
}







